package com.liu.design.building.prototype;

import java.io.*;
import java.util.List;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/5/3 10:40
 * @description TODO
 * 浅拷贝
 *    jdk实现的拷贝功能，需要实现Cloneable接口，底层是基于字节数组实现
 */
public class ConcretePrototype implements Cloneable, Serializable {
    private int age;
    private String name;

    private List<String> hobbies;


    /**
     * 浅拷贝
     * @return
     */
    @Override
    protected ConcretePrototype clone()  {
        try {
            return (ConcretePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     *  使用序列化实现深度克隆
     */
    protected ConcretePrototype deepClone() {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(output);
            oos.writeObject(this);

            ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(input);

            return (ConcretePrototype) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }


    @Override
    public String toString() {
        return "ConcretePrototype{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", hobbies=" + hobbies +
                '}';
    }
}
